/*!
 * Copyright (C) 2020 - All Rights Reserved by
 * @author : ZhaoYanbo
 * @email  : zyb920@hotmail.com
 * @created: 2020-10-31
 * @version: 1.0.0.0
 *
 */

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QDir>
#include <QLockFile>
#include <QQuickWindow>
#include <QScreen>

#include "src/CPixmapCache.h"
#include "src/cmodelmanager.h"

int main(int argc, char *argv[])
{
    //单例进程
    QString path = QDir::temp().absoluteFilePath("image_tools_singleton.lock");
    QLockFile lockFile(path);
    if( !lockFile.tryLock(100) ) {
        return -1;
    }

    QCoreApplication::setAttribute(Qt::AA_DisableHighDpiScaling);
    //QCoreApplication::setAttribute(Qt::AA_Use96Dpi);
    //QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);
    app.setOrganizationName("none");//公司名称
    //app.setOrganizationDomain("http://www.baidu.com");//
    app.setApplicationName("ImageTools");//产品名称
    app.setApplicationVersion("v0.0.1");//版本号

    PixmapCache;//初始化

    QQmlApplicationEngine engine;

    CModelManager mgr;
    mgr.registFuncManager(&engine);

    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    QList<QObject *> list = engine.rootObjects();
    if(list.length() < 1)
        return -1;

    //设置屏幕居中显示
    QQuickWindow *window = qobject_cast<QQuickWindow *>(list.at(0)) ;
    if(window) {
        QScreen *screen = app.screenAt(window->position()); //app.primaryScreen();
        if(!screen)
            return -1;
        QRect rect = screen->availableGeometry();
        window->setPosition(rect.x() + (rect.width()  - window->width())  / 2,
                            rect.y() + (rect.height() - window->height()) / 2);
    }

    return app.exec();
}
